var data=[
    {id:1,name:"前端开发",parent_id:0},
    {id:2,name:"CSS",parent_id:1},
    {id:3,name:"JS",parent_id:1},
    {id:4,name:"HTML",parent_id:1},
    {id:5,name:"数据库",parent_id:0},
    {id:6,name:"SQLServer",parent_id:5},
    {id:7,name:"MYSql",parent_id:5},
    {id:8,name:"Oracle",parent_id:5},
    {id:9,name:"PLSQL",parent_id:8}
];

//无限级 select 分类
function select(arr, chg) {
	//获得子类 集合（select）
    var getSel=function(parent_id)
    {
        var _select = document.createElement("select");
        _select.id = parent_id;
        _select.name = "select["+parent_id+"]";
		_select.options.add(new Option('选择科目',-1));

        for(var i=0;i<arr.length;i++)
        {
            if(arr[i].parent_id == parent_id)
            {
                _select.options.add(new Option(arr[i].name, arr[i].id));
            }
        }
        
        var delChildfun=function(obj) {
            if(obj.child){
                var _child=obj.child;
                
                if(_child.parentNode) {
                    _child.parentNode.removeChild(_child);
                }                
                delChildfun(_child);
            }
        }
		
		_select.onchange=function() {
			delChildfun(this);
			this.child = getSel(this.options[this.selectedIndex].value);
			chg(this.child);
		} 
		return _select;
        
    }
	
	//===================获得节点
	var r_arr = [];
	var getparent_idById = function(id) {
		for(var i=0;i<arr.length;i++)
			if(arr[i].id==id) return arr[i].parent_id;
			
		return -1;
	}

	var getSelBySid=function(id, selectid) 
    {
        // 检查选中情况
        selectid = (selectid == true) ? -1 : id;

		var parent_id = getparent_idById(id);
		
		var sel = getSel(parent_id);

		for(var i=0;i<sel.options.length;i++) 
        {
			if(sel.options[i].value == selectid)
            {
				sel.selectedIndex = i; break;
			}
		}

		if(parent_id>0) getSelBySid(parent_id, false);
		r_arr.push(sel);
	}
	
    this.getDom = function(id, selectid)
    {
		getSelBySid(id||arr[0].id, selectid);
		for(var i=0;i<r_arr.length;i++)
			if(i+1<r_arr.length)
				r_arr[i].child=r_arr[i+1];
		
		return r_arr;
    }
}


/**==============demo==============**/
/*
var demo1 = document.getElementById("demo1");
var chg=function(obj){
	if(obj.options.length>1) {
		obj.selectedIndex=0;
		demo1.appendChild(obj);
	}
}

var sel1 = new select(data, chg);

var _arr= sel1.getDom(2);
for(var i=0;i<_arr.length;i++) {
	demo1.appendChild(_arr[i]);
}
*/
/**==============demo==============**/